package br.com.fiap.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import br.com.fiap.beans.filtro.FiltroCliente;
import br.com.fiap.dao.ClienteDAO;
import br.com.fiap.entity.Cliente;

public class ClienteDAOImpl extends AbstractDAOImpl<Cliente> implements ClienteDAO {

	private static final long serialVersionUID = -2639710791058940976L;

	@Override
	public List<Cliente> findByFilter(FiltroCliente filtro) {

		StringBuilder queryStr = new StringBuilder();

		queryStr.append(" select c from " + Cliente.class.getCanonicalName() + " c ");

		boolean putWhereCaluse = true;

		if (filtro.getCpf() != null && !filtro.getCpf().isEmpty()) {
			if (putWhereCaluse) {
				queryStr.append(" where cpf = :cpf ");
				putWhereCaluse = false;
			} else {
				queryStr.append(" and cpf = :cpf ");
			}
		}

		if (filtro.getEmail() != null && !filtro.getEmail().isEmpty()) {
			if (putWhereCaluse) {
				queryStr.append(" where email = :email ");
				putWhereCaluse = false;
			} else {
				queryStr.append(" and email = :email ");
			}
		}

		if (filtro.getNome() != null && !filtro.getNome().isEmpty()) {
			if (putWhereCaluse) {
				queryStr.append(" where lower(nome) like :nome ");
				putWhereCaluse = false;
			} else {
				queryStr.append(" and lower(nome) = :nome ");
			}
		}

		Session session = getHibernateSession();
		Query query = session.createQuery(queryStr.toString());

		if (filtro.getCpf() != null && !filtro.getCpf().isEmpty()) {
			query.setParameter("cpf", filtro.getCpf());
		}

		if (filtro.getEmail() != null && !filtro.getEmail().isEmpty()) {
			query.setParameter("email", filtro.getEmail());
		}

		if (filtro.getNome() != null && !filtro.getNome().isEmpty()) {
			query.setParameter("nome", "%" + filtro.getNome() + "%");
		}
		
		List<Cliente> clientes = (List<Cliente>) query.list();
		
		session.clear();
		session.close();

		return clientes;
	}

	@Override
	public Class<Cliente> getEntityClass() {
		return Cliente.class;
	}

}
